﻿using App.Chat.Contract;
using Zws.Redis;

namespace App.Chat.Auth
{
    public class AuthenticateMiddleware
    {
        private readonly RequestDelegate _next;

        public AuthenticateMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            var token = context.GetLoginToken();
            var redis = context.RequestServices.GetService<RedisClient>();
            if (token != null && redis != null && await redis.IsExistAsync(token))
            {
                var user = await redis.GetByKeyAsync<CurrentUser>(token);
                var currentUser = context.RequestServices.GetService<CurrentUser>();
                currentUser!.Id = user!.Id;
                currentUser.UserName = user.UserName;
                currentUser.Token = token;
                //TODO 为了让hub能拿到user，把user放到context里面了，看看有没有其它的好办法
                context.Items[CommonConst.ContextItemUserKey] = currentUser;
            }
            await _next(context);
        }
    }
}
